package com.huatao.wx.controller;

import com.huatao.wx.handler.WcChatMsgHandler;
import com.huatao.wx.handler.WxChatMsgFactory;
import com.huatao.wx.util.MessageUtil;
import com.huatao.wx.util.SHA1;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/wx")
public class CallBackController {

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    private static final String token = "asedwiiafcffsad";

    @GetMapping("callback")
    public String callback1(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("signature: {}, timestamp: {}, nonce: {}, echostr: {}", signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknow";
    }

    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("requestBody: {}, signature: {}, timestamp: {}, nonce: {}, msg_signature: {}", requestBody,signature, timestamp, nonce, msgSignature);
        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        String msgType = msgMap.get("MsgType");
        String event = msgMap.get("Event") == null ? "" : msgMap.get("Event");
        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (StringUtils.isEmpty(event)) {
            sb.append(".");
            sb.append(event);
        }
        String msgTypeKey = sb.toString();
        WcChatMsgHandler handlerByMsg = wxChatMsgFactory.getHandlerByMsg(msgTypeKey);
        String replayContent = handlerByMsg.dealMsg(msgMap);
        log.info("replayContent: {}", replayContent);
        return replayContent;
    }

}
